백준 15652번 N과 M

Solution

import sys

input = sys.stdin.readline

n, m = map(int, input().split())

selected = [0] * (m)


def solve(x):
    if x == m + 1:
        for s in selected:
            print(s, end=' ')
        print()
    else:
        # 맨 처음인 경우 1로 설정
        if x - 2 < 0:
            start = 1
        else:
            # 바로 전에 있는 숫자
            start = selected[x - 2]
        for candidate in range(start, n + 1):
            selected[x - 1] = candidate
            solve(x + 1)
            selected[x - 1] = 0


solve(1)
  • 모범 풀이
import sys
n, m = map(int, sys.stdin.readline().split(' '))

selected = [0 for _ in range(m)]
used = [0 for _ in range(n + 1)]
def rec_func(k):
    if k == m:
        for x in selected:
            sys.stdout.write(str(x) + ' ')
        sys.stdout.write('\n')
    else:
        start = 1 if k == 0 else selected[k - 1]
        for cand in range(start, n + 1):
            selected[k] = cand
            rec_func(k + 1)
            selected[k] = 0

rec_func(0)